import { defineStore } from 'pinia'

export type ThemeMode = 'light' | 'dark'

const THEME_KEY = 'theme'

export const useThemeStore = defineStore('theme', {
  state: () => ({ mode: 'light' as ThemeMode }),
  actions: {
    hydrate() {
      const saved = localStorage.getItem(THEME_KEY) as ThemeMode | null
      if (saved === 'dark' || saved === 'light') this.mode = saved
      this.apply()
    },
    set(mode: ThemeMode) {
      this.mode = mode
      localStorage.setItem(THEME_KEY, mode)
      this.apply()
    },
    toggle() {
      this.set(this.mode === 'dark' ? 'light' : 'dark')
    },
    apply() {
      const root = document.documentElement
      if (this.mode === 'dark') {
        root.classList.add('dark')
      } else {
        root.classList.remove('dark')
      }
    }
  }
})
